package com.ptl.bp.config;

import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class ApiResult<T> {
    @Schema(title = "HTTP状态码", example = "200")
    private ResStatusEnum code;  // 使用枚举，但通过@JsonValue序列化为数字

    @Schema(title = "返回的数据", example = "{\"name\":\"tom\"}")
    private T data;

    @Schema(title = "返回的提示信息", example = "操作成功")
    private String message;

    // ---------- 静态工厂方法 ----------
    public static <T> ApiResult<T> success(T data) {
        return new ApiResult<>(ResStatusEnum.SUCCESS, data, "操作成功");
    }

    public static <T> ApiResult<T> fail(String message) {
        return new ApiResult<>(ResStatusEnum.BAD_REQUEST, null, message);
    }

    public static <T> ApiResult<T> fail(String message, T data) {
        return new ApiResult<>(ResStatusEnum.BAD_REQUEST, data, message);
    }
    public static <T> ApiResult<T> unauthorized(String message) {
        return new ApiResult<>(ResStatusEnum.UNAUTHORIZED, null, message);
    }
    public static <T> ApiResult<T> exception(String message) {
        return new ApiResult<>(ResStatusEnum.INTERNAL_SERVER_ERROR, null, message);
    }

    public static <T> ApiResult<T> response(ResStatusEnum code, T data, String message) {
        return new ApiResult<>(code, data, message);
    }


    // ---------- 枚举定义 ----------
    @Getter
    @Schema(title = "HTTP状态码枚举")
    public enum ResStatusEnum {
        SUCCESS(200, "成功"),
        BAD_REQUEST(400, "请求错误"),
        UNAUTHORIZED(401, "未授权"),
        FORBIDDEN(403, "禁止访问"),
        NOT_FOUND(404, "资源不存在"),
        INTERNAL_SERVER_ERROR(500, "服务器错误");

        @JsonValue  // 关键注解：让枚举序列化为code值
        private final int code;
        private final String desc;

        ResStatusEnum(int code, String desc) {
            this.code = code;
            this.desc = desc;
        }
    }
}